package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.util.Date;
import java.util.UUID;

/**
 * @author terminal
 * @since 2023-06-08 10:10
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Resource
    private MinioClient minioClient;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    /**
     * 文件上传
     *
     * @param file
     * @return 上传后在线图片地址
     */
    public String fileUpload(MultipartFile file) {
        try {
            // 1 判断minio有没有gmall  有就用 没有创建
            boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!flag) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            // 2 手动给一个文件路径 UUID
            String date = DateUtil.formatDate(new Date());
            String fileName = UUID.randomUUID().toString();
            String after = StringUtils.substringAfter(file.getOriginalFilename(), ".");
            fileName = date + "/" + fileName + "/" + after;
            // 3 调用MinIO客户端对象 将文件上传到MinIO中
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            // 4 返回上传后图片在线地址,方便前端进行图片预览
            return endpointUrl + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
